package com.dandelion.manager.commons.tag;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.dandelion.commons.utils.StringUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

@SuppressWarnings("rawtypes")
public class SessionPrincipalTag implements TemplateDirectiveModel {

	/**
	 * freemarker自定义函数
	 * 页面中调用(ftl)
	 * <@principal sessionId="${session.id}"></@principal>
	 */
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String sessionId = getRequiredParam(params, "sessionId");
		Writer out = env.getOut() ;
		out.write(sessionId);
		body.render(out);
	}

	static String getRequiredParam(Map params, String key) throws TemplateException {
		Object value = params.get(key);
		if (value == null || StringUtils.isEmpty(value.toString())) {
			throw new TemplateModelException("not found required parameter:" + key + " for directive");
		}
		return value.toString();
	}
}
